package com.lzy.sso.cas.store.impl;

import com.lzy.sso.cas.pojo.Identification;
import com.lzy.sso.cas.store.TokenManagement;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lzy
 * @Date: 2022/4/25 17:20
 * @Description: token管理 本地存储 单机适用
 */

//@Component
//@ConditionalOnProperty(name = "lzy.cas.session.store",havingValue = "local")
public class LocalTokenManagement implements TokenManagement {
    private Map<String,Long> tokens=new ConcurrentHashMap<String, Long>();
    private Map<String, Identification> ids=new ConcurrentHashMap<>();

    /**
     * 检测token的合法性: 1.存在 2.期限
     * @param token
     * @return
     */
    public boolean exists(String token){
        if(!tokens.containsKey(token)){
            return false;
        }

        Long expire=tokens.get(token);
        if(expire>= System.currentTimeMillis()){
            //未过期
            return true;
        }

        //惰性删除
        ids.remove(token);
        tokens.remove(token);
        return false;
    }

    /**
     * 添加新token
     * @param token
     * @param expires
     * @return
     */
    public void addToken(String token,Identification identification,long expires){
        ids.put(token,identification);
        tokens.put(token,System.currentTimeMillis()+expires);
    }

    /**
     * 添加token
     * @param token
     * @param identification
     */
    @Override
    public void addToken(String token, Identification identification) {
        this.addToken(token,identification,1000*60*30);
    }

    /**
     * 本地取
     * @param token
     * @return
     */
    @Override
    public Identification getIdentification(String token) {
        return ids.get(token);
    }
}
